package com.ybkj.daijia.api.weixin.v1;

import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.OrderNewRushEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.OrderCarType;
import com.ybkj.daijia.server.model.Order.OrderCarTypeDetail;
import com.ybkj.daijia.server.model.PhoneSmsRecord;
import com.ybkj.daijia.server.model.WeixinManager;
import com.ybkj.daijia.server.model.WeixinManagerTixianRecord;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.PhoneSmsRecordService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.WeixinManagerService;
import com.ybkj.daijia.server.service.WeixinManagerTixianRecordService;
import com.ybkj.daijia.server.service.WeixinManagerXOrderService;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 客户经理相关
 *
 * @author mqs
 */
@Controller
@RequestMapping(value = "wx/v1/ConsumerManager")
public class WxConsumerManager {

    private static final Logger logger = LoggerFactory.getLogger(WxConsumerManager.class);

    @Autowired
    private WeixinManagerService weixinManagerService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private WeixinManagerXOrderService weixinManagerXOrderService;

    @Autowired
    private WeixinManagerTixianRecordService weixinManagerTixianRecordService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private PhoneSmsRecordService phoneSmsRecordService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private SmsService smsService;

    @RequestMapping(value = {"", "/"})
    public String index() {

        return null;
    }

    @RequestMapping("profile")
    public String profile(Model model, String wxuser) {

        model.addAttribute("wxuser", wxuser);

        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return "wxmanagerweb/apply";//审核失败
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    model.addAttribute("message", "您还未审核通过，请耐心等待");
                    return "wxmanagerweb/message";//待审
                }

                model.addAttribute("weixinManager", wm);
                return "wxmanagerweb/profile";//个人中心

            }
            model.addAttribute("message", "您还未申请客户经理");
            return "wxmanagerweb/apply";//还未申请过
        }

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("redirectUrl", "wx/v1/ConsumerManager/profile");
        model.addAttribute("message", "微信账号为空");
        return "wxmanagerweb/message";//微信账号为空

    }

    @RequestMapping("orderRecords")
    public String orderRecords(Model model, String wxuser,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "limit") Integer limit) {

        model.addAttribute("wxuser", wxuser);

        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return "wxmanagerweb/apply";//审核失败
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    model.addAttribute("message", "您还未审核通过，请耐心等待");
                    return "wxmanagerweb/message";//待审
                }

                if (null == page) {
                    page = 0;
                }
                if (null == limit) {
                    limit = 10;
                }

                model.addAttribute("weixinxorders",
                    weixinManagerXOrderService.queryByManagerId(wm.getId(), page, limit));
                return "wxmanagerweb/orderrecords";//订单记录

            }
            return "wxmanagerweb/apply";//还未申请过
        }

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("redirectUrl", "wx/v1/ConsumerManager/orderRecords");
        model.addAttribute("message", "微信账号为空");
        return "wxmanagerweb/message";//微信账号为空

    }

    @RequestMapping("orderRecordsData")
    public @ResponseBody
    Page<Map<String, Object>> orderRecordsData(
        String wxuser,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "limit") Integer limit) {

        Page<Map<String, Object>> result = null;
        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return result;
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    return result;
                }

                if (null == page) {
                    page = 0;
                }
                if (null == limit) {
                    limit = 10;
                }

                result = weixinManagerXOrderService.queryByManagerId(wm.getId(), page, limit);
                return result;

            }
        }
        return result;

    }

    @RequestMapping("tixianRecords")
    public String tixianRecords(Model model, String wxuser,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "limit") Integer limit) {

        model.addAttribute("wxuser", wxuser);

        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return "wxmanagerweb/apply";//审核失败
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    model.addAttribute("message", "您还未审核通过，请耐心等待");
                    return "wxmanagerweb/message";//待审
                }

                if (null == page) {
                    page = 0;
                }
                if (null == limit) {
                    limit = 10;
                }

                model.addAttribute("tixianrecords", weixinManagerTixianRecordService
                    .queryAll(wm.getId(), page, limit, null, null, null));
                return "wxmanagerweb/tixianrecords";//订单记录

            }
            return "wxmanagerweb/apply";//还未申请过
        }

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("redirectUrl", "wx/v1/ConsumerManager/tixianRecords");
        model.addAttribute("message", "微信账号为空");
        return "wxmanagerweb/message";//微信账号为空

    }

    @RequestMapping("tixianRecordsData")
    public @ResponseBody
    Page<WeixinManagerTixianRecord> tixianRecordsData(
        String wxuser,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "limit") Integer limit) {

        Page<WeixinManagerTixianRecord> result = null;
        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return result;
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    return result;
                }

                if (null == page) {
                    page = 0;
                }
                if (null == limit) {
                    limit = 10;
                }

                result = weixinManagerTixianRecordService
                    .queryAll(wm.getId(), page, limit, null, null, null);
                return result;

            }
        }
        return result;

    }

    @RequestMapping("applyTixian")
    public String applyTixian(Model model, String wxuser) {

        model.addAttribute("wxuser", wxuser);

        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return "wxmanagerweb/apply";//审核失败
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    model.addAttribute("message", "您还未审核通过，请耐心等待");
                    return "wxmanagerweb/message";//待审
                }

                model.addAttribute("weixinManager", wm);
                return "wxmanagerweb/applytixian";

            }
            return "wxmanagerweb/apply";//还未申请过
        }

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("redirectUrl", "wx/v1/ConsumerManager/applyTixian");
        model.addAttribute("message", "微信账号为空");
        return "wxmanagerweb/message";//微信账号为空

    }

    @RequestMapping("applyTixianPost")
    public String applyTixian(Model model, WeixinManagerTixianRecord weixinManagerTixianRecord,
        String wxuser) {

        model.addAttribute("wxuser", wxuser);

        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return "wxmanagerweb/apply";//审核失败
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    model.addAttribute("message", "您还未审核通过，请耐心等待");
                    return "wxmanagerweb/message";//待审
                }

                if (weixinManagerTixianRecord.getMoney().compareTo(BigDecimal.ZERO) == 1) {

                    if (wm.getVirtual().subtract(weixinManagerTixianRecord.getMoney())
                        .compareTo(BigDecimal.ZERO) == -1) {
                        model.addAttribute("message", "余额不足！");
                        return "wxmanagerweb/message";
                    }

                    weixinManagerTixianRecordService.tixianApply(weixinManagerTixianRecord, wm);
                    model.addAttribute("message", "申请提现成功");
                    return "wxmanagerweb/message";

                } else {
                    model.addAttribute("message", "无效的金额");
                    return "wxmanagerweb/message";
                }

            }
            return "wxmanagerweb/apply";//还未申请过
        }

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("redirectUrl", "wx/v1/ConsumerManager/applyTixianPost");
        model.addAttribute("message", "微信账号为空");
        return "wxmanagerweb/message";//微信账号为空

    }

    @RequestMapping("bind")
    public String bind(Model model, String wxuser) {

        model.addAttribute("wxuser", wxuser);

        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_OK)) {
                    model.addAttribute("message", "您已经是客户经理，不能重复申请");
                    return "wxmanagerweb/message";//微信账号为空
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return "wxmanagerweb/apply";//审核失败
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    model.addAttribute("message", "您还未审核通过，请耐心等待");
                    return "wxmanagerweb/message";//待审
                }
            }
            return "wxmanagerweb/bind";
        }

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("redirectUrl", "wx/v1/ConsumerManager/bind");
        model.addAttribute("message", "微信账号为空");
        return "wxmanagerweb/message";//微信账号为空

    }

//	@RequestMapping("smsQrCode")
//	public @ResponseBody Result<PhoneSmsRecord> smsQrCode(String phone){
//		
//		Result<PhoneSmsRecord> result=new Result<PhoneSmsRecord>();
//		
//		Company company=companyService.getMain();
//		
//		PhoneSmsRecord phoneSmsRecord=phoneSmsRecordService.findByPhone(phone);
//		if(null!=phoneSmsRecord){
//			long time=(System.currentTimeMillis()-phoneSmsRecord.getExpired().getTime())/1000;//多少秒
//			if(time<120){//2分内禁止发送
//				result.setErrorcode("0");
//				result.setObject(120-time);
//				return result;
//			}
//			else if(time>=120 && time<30*60){//30分内发送旧的
//				result.setErrorcode("1");
//				int code=-99;
//				try{
//					String con="尊敬的用户您好,验证码："+phoneSmsRecord.getVcode();
//					SmsTemplet templet = smsService.findByAlias(company.getId(), SmsType.customMember);
//					if(templet==null){
//						SmsTemplet smsTemplet=new SmsTemplet();
//						smsTemplet.setCompanyId(company.getId());
//						smsTemplet.setContent("{content}");
//						smsTemplet.setSmsType(SmsType.customMember);
//						smsService.insertSmsTemplate("给客户发自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//					}
//					if(templet != null && StringUtils.isNotBlank(templet.getContent())){
//						code=smsService.sendSms(phone, "customMember", "{\"content\":\""+con+"\"}",company.getId(), 2, company.getSignName());
//					}
//				}
//				catch(Exception e){
//				}
//				logger.debug("验证码发送结果："+code+"，验证码："+phoneSmsRecord.getVcode());
//				if(code==0){
//					result.setSuccess(true);
//					phoneSmsRecord.setExpired(new Date());
//					phoneSmsRecordService.update(phoneSmsRecord);
//				}
//				return result;
//			}
//			else{//超过30分 发送新的
//				result.setErrorcode("1");
//				String newCode=String.valueOf(RandomString.randomNum(4));
//				int code=-99;
//				try{
//					String con="尊敬的用户您好,验证码："+newCode;
//					SmsTemplet templet = smsService.findByAlias(company.getId(), SmsType.customMember);
//					if(templet==null){
//						SmsTemplet smsTemplet=new SmsTemplet();
//						smsTemplet.setCompanyId(company.getId());
//						smsTemplet.setContent("{content}");
//						smsTemplet.setSmsType(SmsType.customMember);
//						smsService.insertSmsTemplate("给客户发自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//					}
//					if(templet != null && StringUtils.isNotBlank(templet.getContent())){
//						code=smsService.sendSms(phone, "customMember", "{\"content\":\""+con+"\"}",company.getId(), 2, company.getSignName());
//					}
//				}
//				catch(Exception e){
//				}
//				logger.debug("验证码发送结果："+code+"，验证码："+newCode);
//				if(code==0){
//					result.setSuccess(true);
//					phoneSmsRecord.setExpired(new Date());
//					phoneSmsRecord.setVcode(newCode);
//					phoneSmsRecordService.update(phoneSmsRecord);
//				}
//				return result;
//			}
//		}
//		else{
//			result.setErrorcode("1");
//			String newCode=String.valueOf(RandomString.randomNum(4));
//			int code=-99;
//			try{
//				String con="尊敬的用户您好,验证码："+newCode;
//				SmsTemplet templet = smsService.findByAlias(company.getId(), SmsType.customMember);
//				if(templet==null){
//					SmsTemplet smsTemplet=new SmsTemplet();
//					smsTemplet.setCompanyId(company.getId());
//					smsTemplet.setContent("{content}");
//					smsTemplet.setSmsType(SmsType.customMember);
//					smsService.insertSmsTemplate("给客户发自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//				}
//				if(templet != null && StringUtils.isNotBlank(templet.getContent())){
//					code=smsService.sendSms(phone, "customMember", "{\"content\":\""+con+"\"}",company.getId(), 2, company.getSignName());
//				}
//			}
//			catch(Exception e){
//			}
//			logger.debug("验证码发送结果："+code+"，验证码："+newCode);
//			if(code==0){
//				result.setSuccess(true);
//				phoneSmsRecord=new PhoneSmsRecord();
//				phoneSmsRecord.setCompanyId(company.getId());
//				phoneSmsRecord.setExpired(new Date());
//				phoneSmsRecord.setPhone(phone);
//				phoneSmsRecord.setVcode(newCode);
//				phoneSmsRecordService.save(phoneSmsRecord);
//			}
//			
//			return result;
//		}
//		
//	}

    @RequestMapping(value = "bindPost", method = RequestMethod.POST)
    public String bindPost(Model model, String wxuser, String phone, String code) {

        logger.debug("recv wxuser:{},phone:{},code:{}",
            wxuser, phone, code);

        if (StringUtils.isBlank(wxuser) || StringUtils.isBlank(phone) || StringUtils
            .isBlank(code)) {
            model.addAttribute("message", "参数错误");
            return "wxmanagerweb/message";
        }

        PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);
        if (null == phoneSmsRecord || !phoneSmsRecord.getVcode().equals(code)) {
            model.addAttribute("message", "验证码错误");
            return "wxmanagerweb/message";
        }

        WeixinManager old = weixinManagerService.findByPhone(phone);

        if (null == old) {
            model.addAttribute("message", "该手机号码还不是客户经理");
            return "wxmanagerweb/message";
        } else {
            if (StringUtils.isNotBlank(old.getWxuser())) {
                model.addAttribute("message", "您已经是客户经理");
                return "wxmanagerweb/message";
            }

            old.setWxuser(wxuser);
            weixinManagerService.updateByPrimaryKey(old);

        }
        model.addAttribute("message", "绑定成功");
        return "wxmanagerweb/message";
    }


    /**
     * 申请成为客户经理
     *
     * @param wxuser
     * @return
     */
    @RequestMapping("apply")
    public String apply(Model model, String wxuser) {

        model.addAttribute("wxuser", wxuser);

        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_OK)) {
                    model.addAttribute("message", "您已经是客户经理，不能重复申请");
                    return "wxmanagerweb/message";//微信账号为空
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return "wxmanagerweb/apply";//审核失败
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    model.addAttribute("message", "您还未审核通过，请耐心等待");
                    return "wxmanagerweb/message";//待审
                }
            }
            return "wxmanagerweb/apply";//还未申请过
        }

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("redirectUrl", "wx/v1/ConsumerManager/apply");
        model.addAttribute("message", "微信账号为空");
        return "wxmanagerweb/message";//微信账号为空

    }

    @RequestMapping(value = "applyCompanys", method = RequestMethod.GET)
    public @ResponseBody
    List<Company> applyCompanys() {
        return companyService.findAll();
    }


    @RequestMapping(value = "applyPost", method = RequestMethod.POST)
    public @ResponseBody
    Result<WeixinManager> applyPost(WeixinManager weixinManager) {

        logger.debug(
            "recv place:{},lat:{},lng:{},wxuser:{},name:{},phone:{},idCard:{},jobNumber:{},personalInfo{}",
            weixinManager.getPlace(), weixinManager.getLatitude(), weixinManager.getLongitude(),
            weixinManager.getWxuser(),
            weixinManager.getName(), weixinManager.getPhone(), weixinManager.getIdCard(),
            weixinManager.getJobNumber(), weixinManager.getPersonalInfo());

        Result<WeixinManager> vo = new Result<WeixinManager>();
        vo.setSuccess(false);

        if (StringUtils.isBlank(weixinManager.getPlace()) || null == weixinManager.getLatitude()
            || null == weixinManager.getLongitude() || StringUtils
            .isBlank(weixinManager.getWxuser())
            || StringUtils.isBlank(weixinManager.getName()) || StringUtils
            .isBlank(weixinManager.getPhone())) {
            vo.setMessage("参数错误");
            return vo;
        }

        WeixinManager old = weixinManagerService.findByWxuser(weixinManager.getWxuser());

        if (null == old) {
            if (phoneExists(weixinManager.getPhone(), null)) {
                vo.setMessage("手机号" + weixinManager.getPhone() + "已申请过客户经理");
                return vo;
            }
//			if(idCardExists(weixinManager.getIdCard(),null)){
//				vo.setMessage("身份证号"+weixinManager.getPhone()+"已申请过客户经理");
//				return vo;
//			}

            weixinManager.setVirtual(BigDecimal.ZERO);
            weixinManager.setStatus(WeixinManager.WEIXINMANAGER_STATUS_NOTYET);
            weixinManagerService.insertRecord(weixinManager);

        } else {
            if (old.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                vo.setMessage("您已申请过，请耐心等待");
                return vo;
            }
            if (old.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_OK)) {
                vo.setMessage("您已经是客户经理,不能重复申请");
                return vo;
            }
            if (phoneExists(weixinManager.getPhone(), old.getId())) {
                vo.setMessage("手机号" + weixinManager.getPhone() + "已申请过客户经理");
                return vo;
            }
//			if(idCardExists(weixinManager.getIdCard(),old.getId())){
//				vo.setMessage("身份证号"+weixinManager.getPhone()+"已申请过客户经理");
//				return vo;
//			}

            old.setIdCard(weixinManager.getIdCard());
            old.setJobNumber(weixinManager.getJobNumber());
            old.setName(weixinManager.getName());
            old.setPersonalInfo(weixinManager.getPersonalInfo());
            old.setPhone(weixinManager.getPhone());
            old.setPlace(weixinManager.getPlace());
            old.setLatitude(weixinManager.getLatitude());
            old.setLongitude(weixinManager.getLongitude());
            old.setCompanyId(weixinManager.getCompanyId());

            old.setStatus(WeixinManager.WEIXINMANAGER_STATUS_NOTYET);
            weixinManagerService.updateByPrimaryKey(old);

        }

        vo.setSuccess(true);
        return vo;
    }


    /**
     * 客户经理点击下单
     *
     * @param wxuser
     * @return
     */
    @RequestMapping("book")
    public String book(Model model, String wxuser) {

        model.addAttribute("wxuser", wxuser);

        if (StringUtils.isNotBlank(wxuser)) {

            WeixinManager wm = weixinManagerService.findByWxuser(wxuser);

            if (null != wm) {
                if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_OK)) {
                    model.addAttribute("weixinManager", wm);
                    return "wxmanagerweb/book";
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    return "wxmanagerweb/apply";//审核失败
                } else if (wm.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    model.addAttribute("message", "您还未审核通过，请耐心等待");
                    return "wxmanagerweb/message";//待审
                }
            }
            return "wxmanagerweb/apply";//还未申请过
        }

        model.addAttribute("setting", settingUtils.getWx());
        model.addAttribute("redirectUrl", "wx/v1/ConsumerManager/book");
        model.addAttribute("message", "微信账号为空");
        return "wxmanagerweb/message";//微信账号为空
    }

    @RequestMapping(value = "bookPost", method = RequestMethod.POST)
    public @ResponseBody
    Result<Order> bookPost(Long id, Double longitude, Double latitude, String place,
        Integer driverNum, String clientPhone, String clientName) {

        logger.debug(
            "recv id:{},longitude:{},latitude:{},place:{},driverNum:{},clientPhone:{},clientName:{}",
            id, longitude, latitude, place, driverNum, clientPhone, clientName);

        Result<Order> vo = new Result<Order>();
        vo.setSuccess(false);

        if (null == id || null == longitude || null == latitude || StringUtils.isBlank(place)
            || null == driverNum || StringUtils.isBlank(clientPhone)) {
            vo.setMessage("参数错误");
            return vo;
        }

        WeixinManager weixinManager = weixinManagerService.findOne(id);

        if (null == weixinManager) {
            vo.setMessage("您还不是客户经理");
            return vo;
        }

        if (!weixinManager.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_OK)) {
            vo.setMessage("您申请的客户经理还未审核通过");
            return vo;
        }

        if (driverNum <= 0) {
            vo.setMessage("所需服务人员数量最少为1人");
            return vo;
        }

        if (driverNum > 5) {
            vo.setMessage("所需服务人员数量最多为5人");
            return vo;
        }

        try {
            Order order = new Order();
            order.setClientLongitude(longitude);
            order.setClientLatitude(latitude);
            order.setFromPlace(URLDecoder.decode(place, "UTF-8"));
            order.setServerTime(new Date());
            order.setClientPhone(clientPhone);
            order.setClientName(URLDecoder.decode(clientName, "UTF-8"));
            order.setOrderCarType(OrderCarType.daijia);
            order.setOrderCarTypeDetail(OrderCarTypeDetail.jhdj);

            Passenger passenger = memberService.findOnePassengerByPhone(order.getClientPhone());

            List<Order> orderlist = orderService.managerBook(weixinManager, order, driverNum);

            OrderNewRushEvent newRushEvent = new OrderNewRushEvent(orderlist);
            applicationEventMulticaster.multicastEvent(newRushEvent);

            if (null == passenger) {
                passenger = memberService.findOnePassengerByPhone(order.getClientPhone());
                ReactorVo rVo = new ReactorVo();
                rVo.setPassenger(passenger);
                rVo.setActivityEvent(ActivityEvent.newRegister);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);
            }
            vo.setSuccess(true);
            return vo;
        } catch (Exception e) {
            vo.setMessage(e.getMessage());
            return vo;
        }
    }

    private boolean idCardExists(String idCard, Long id) {
        WeixinManager wm = weixinManagerService.findByIdCard(idCard);

        if (null != wm) {

            if (null != id && id.equals(wm.getId())) {

                return false;

            }

            return true;
        }

        return false;
    }

    private boolean phoneExists(String phone, Long id) {
        WeixinManager wm = weixinManagerService.findByPhone(phone);

        if (null != wm) {

            if (null != id && id.equals(wm.getId())) {

                return false;

            }

            return true;
        }

        return false;
    }

}

